﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace ProtoBuf
{
    public static class Support
    {
        private static ILRuntime.Runtime.Enviorment.AppDomain _appDomain;
        private static readonly Dictionary<string, Type> TypeDic = new Dictionary<string, Type>();
        
        public static void RegisterILRuntime(ILRuntime.Runtime.Enviorment.AppDomain appDomain)
        {
            _appDomain = appDomain;
        
            foreach (var loadedTypesValue in _appDomain.LoadedTypes.Values)
            {
               TypeDic[loadedTypesValue.FullName] = loadedTypesValue.ReflectionType;
            }
        }

        public static Type FindType(string metaName)
        {
            if (!TypeDic.TryGetValue(metaName, out var type))
            {
                throw new SystemException($"PropertyMeta : {metaName} is not registered!");
            }

            return type;
        }

        public static object CreateInstance(Type type)
        {
            // ReSharper disable once AssignNullToNotNullAttribute
            if (Type.GetType(type.FullName) == null)
            {
                return _appDomain.Instantiate(type.FullName);
            }

            return Activator.CreateInstance(type
#if !(CF || SILVERLIGHT || WINRT || PORTABLE || NETSTANDARD1_3 || NETSTANDARD1_4)
                , nonPublic: true
#endif
            );
        }

        public static Type GetPType(object obj)
        {
            if (obj is ILRuntime.Runtime.Intepreter.ILTypeInstance instance)
            {
                return instance.Type.ReflectionType;
            }
            
            return obj.GetType();
        }
    }
}
